package base;

import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.Status;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestngListener implements ITestListener {
    public WebDriver driver;
    Base base = new Base();

    //当一个测试用例刚开始执行的时候
    @Override
    public void onTestStart(ITestResult iTestResult) {

        System.out.println(("*** 运行测试方法 " + iTestResult.getMethod().getMethodName() + "..."));
        String testname = iTestResult.getMethod().getMethodName();
        ExtentTestManager.startTest(testname);
    }

    //测试用例运行成功
    @Override
    public void onTestSuccess(ITestResult iTestResult) {
        //ExtentTestManager.getTest()方法获取到当前的测试实例，.log(Status.PASS)测试成功的状态写到测试报告
        ExtentTestManager.getTest().log(Status.PASS, "测试 通过");
    }

    //测试用例失败监听
    @Override
    public void onTestFailure(ITestResult iTestResult) {
        //获取driver实例，完成driver从base类到 用例 到 TestngListener的传递
        this.driver = ((Base) iTestResult.getInstance()).driver;
        //获取失败用例的名称
        String testcaseName = iTestResult.getName().trim();
        //获取当前日期，并按指定格式保存为string类型
        String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
        //截图名称
        String screenShotName = testcaseName + "_" + timeStamp;
        try {
            base.takeScreenshot(screenShotName, driver);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将失败截图附到Extent Report测试报告中
        try {
            ExtentTestManager.getTest().fail("Screenshot",
                    MediaEntityBuilder.createScreenCaptureFromPath(System.getProperty("user.dir") + "\\ScreenShots\\" + screenShotName + ".png").build());
        } catch (IOException e) {
            System.out.println(e.getCause());
        }
        //测试报告
        System.out.println("*** 测试执行 " + iTestResult.getMethod().getMethodName() + " 失败...");
        ExtentTestManager.getTest().log(Status.FAIL, "测试 未通过");
        ExtentTestManager.getTest().log(Status.FAIL, iTestResult.getThrowable()); //抛的异常写进测试报告

    }

    @Override
    public void onTestSkipped(ITestResult iTestResult) {

    }

    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {

    }

    @Override
    public void onStart(ITestContext iTestContext) {

    }

    //
    @Override
    public void onFinish(ITestContext iTestContext) {
        //ExtentTestManager.endTest();
        System.out.println(("*** Test Suite " + iTestContext.getName() + " ending ***"));
        ExtentTestManager.endTest();
    }
}
